package com.gitee.cirnochat.chatai.model.dto.lke;

import com.tencentcloudapi.common.CommonClient;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;

/**
 * 腾讯云Token对象
 * @author FlanChan
 */
@Data
@Slf4j
public class TencentCloudLkeToken {
    /**
     * 腾讯云AKSK密钥ID
     */
    private String secretId;
    /**
     * 腾讯云AKSK密钥
     */
    private String secretKey;
    /**
     * 连接类型，5表示API访客
     */
    private int connTypeApi;
    /**
     * 机器人密钥，不是BotBizId
     */
    private String appKey;
    /**
     * 访客 ID（外部系统提供，需确认不同的访客使用不同的 ID）
     */
    private String visitorBizId;
    /**
     * 腾讯云LKE的区域
     */
    private String region;
    /**
     * 腾讯云LKE的版本
     */
    private String version;

    private static final String ROOT_DOMAIN = "tencentcloudapi.com";


    /**
     * 获取WS客户端连接所需token
     * @return token {@link String}
     */
    public String getWsToken() {
        try {
            if (secretId == null || secretKey == null || appKey == null || visitorBizId == null) {
                log.error("TencentCloudLkeToken is not fully initialized. Please set all required fields.");
                throw new IllegalStateException("TencentCloudLkeToken is not fully initialized.");
            }
            Credential cred = new Credential(secretId, secretKey);

            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setRootDomain(ROOT_DOMAIN);
            httpProfile.setReqMethod(HttpProfile.REQ_POST);
            httpProfile.setProtocol(HttpProfile.REQ_HTTPS);

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            CommonClient client = new CommonClient("lke", version, cred, region, clientProfile);
            JSONObject params = new JSONObject();
            params.put("Type", connTypeApi);
            params.put("BotAppKey", appKey);
            params.put("VisitorBizId", visitorBizId);
            String respJsonStr = client.call("GetWsToken", params.toString());

            JSONObject resp = new JSONObject(respJsonStr);
            JSONObject respData = resp.getJSONObject("Response");
            return respData.getString("Token");
        } catch (Exception e) {
            log.error("Error while getting WS token: {}", e.getMessage(), e);
            throw new RuntimeException("Failed to get WS token", e);
        }
    }
    public static class TencentCloudLkeTokenBuilder {
        private final TencentCloudLkeTokenBuilderOptions options = new TencentCloudLkeTokenBuilderOptions();

        public static TencentCloudLkeTokenBuilder builder() {
            return new TencentCloudLkeTokenBuilder();
        }

        public TencentCloudLkeTokenBuilder setSecretId(String id) {
            options.secretId = id;
            return this;
        }

        public TencentCloudLkeTokenBuilder setSecretKey(String key) {
            options.secretKey = key;
            return this;
        }

        public TencentCloudLkeTokenBuilder setConnTypeApi(int type) {
            options.connTypeApi = type;
            return this;
        }

        public TencentCloudLkeTokenBuilder setAppKey(String key) {
            options.appKey = key;
            return this;
        }

        public TencentCloudLkeTokenBuilder setVisitorBizId(String bizId) {
            options.visitorBizId = bizId;
            return this;
        }

        public TencentCloudLkeTokenBuilder setRegion(String region) {
            options.region = region;
            return this;
        }

        public TencentCloudLkeTokenBuilder setVersion(String version) {
            options.version = version;
            return this;
        }

        public TencentCloudLkeToken build() {
            TencentCloudLkeToken token = new TencentCloudLkeToken();
            token.setSecretId(options.secretId);
            token.setSecretKey(options.secretKey);
            token.setAppKey(options.appKey);
            token.setConnTypeApi(options.connTypeApi);
            token.setVisitorBizId(options.visitorBizId);
            token.setRegion(options.region);
            token.setVersion(options.version);
            options.reset(); // 重置选项以便下次使用
            return token;
        }

        private static class TencentCloudLkeTokenBuilderOptions {
            private String secretId;
            private String secretKey;
            private int connTypeApi;
            private String appKey;
            private String visitorBizId;
            private String region;
            private String version;

            public void reset() {
                this.secretId = null;
                this.secretKey = null;
                this.connTypeApi = 5; // 默认API访客
                this.appKey = null;
                this.visitorBizId = null;
                this.region = null;
                this.version = null;
            }
        }
    }
}
